package com.cat.dataStructure02;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimum-remove-to-make-valid-parentheses/
 * @create 2025/10/20 18:04
 * @since JDK17
 */

public class Solution31 {
    public String minRemoveToMakeValid(String s) {
        int n = s.length(), top = 0, cnt = 0;
        int[] stack = new int[n];
        boolean[] remove = new boolean[n];
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack[top++] = i;
            } else if (c == ')') {
                if (top > 0) {
                    top--;
                } else {
                    remove[i] = true;
                }
            }
        }
        for (int i = 0; i < top; i++) {
            remove[stack[i]] = true;
        }
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (!remove[i]) {
                ans.append(s.charAt(i));
            }
        }

        return ans.toString();
    }
}
